import Vue from 'vue'
import VueRouter from 'vue-router'
import TeacherHomePage from '../views/TeacherHomeView.vue'
import store from '@/store'
import { sendTicket, getUserById } from "@/api/user";
import { getRole } from "@/api/role";
import { login } from "@/api/user"


Vue.use(VueRouter)
const routerPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  return routerPush.call(this, location).catch(err => { })
}

const routes = [
  {
    path: '/',
    name: 'home',
    component: () => import('../views/HomeView.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginView.vue'),
  },
  {
    path: '/teacher',
    name: 'TeacherHome',
    component: TeacherHomePage,
    // meta: { roles: ['teacher'] }
  },
  {
    path: '/student',
    name: 'StudentHome',
    component: () => import('../views/StudentHomeView.vue'),
    // meta: { roles: ['student'] } // 只有学生可以访问
  },
  {
    path: '/authorityCenter',
    name: 'authorityCenter',
    redirect: "/userManage",
    component: () => import('../views/AuthorityCenter/index.vue'),
    children: [
      {
        path: '/userManage',
        name: 'userManage',
        component: () => import('../views/AuthorityCenter/user.vue'),
        meta: {
          title: "用户管理"
        }
      },
      {
        path: '/role',
        name: 'role',
        component: () => import('../views/AuthorityCenter/role.vue'),
        meta: {
          title: "角色管理"
        }
      }
    ]
  },
  {
    path: '/applicationCenter',
    name: 'applicationCenter',
    component: () => import('../views/ApplicationCenterView.vue'),
  },
  {
    path: '/application-phone',
    name: 'application',
    component: () => import('../views/phonePages/application.vue'),
  },
  {
    path: '/notification',
    name: 'notification',
    component: () => import('../views/Notic/NotificationAnnouncement.vue')
  },
  {
    path: '/noticDetail',
    name: 'noticDetail',
    component: () => import('../views/Notic/NoticDetail.vue')
  },
  {
    path: '/noticDetailPhone',
    name: 'noticDetailPhone',
    component: () => import('../views/phonePages/noticDetail.vue')
  },
  {
    path: '/noticAdd',
    name: 'noticAdd',
    component: () => import('../views/Notic/NoticAdd.vue')
  },
  {
    path: '/noticEdit',
    name: 'noticEdit',
    component: () => import('../views/Notic/NoticEdit.vue')
  },
  {
    path: '/myNotic',
    name: 'myNotic',
    component: () => import('../views/Notic/MyNotic.vue')
  },
  {
    path: '/task',
    name: 'task',
    component: () => import('../views/Task/Index.vue')
  },
  {
    path: '/user',
    name: 'user',
    redirect: "/user-profile",
    component: () => import('../views/user/index.vue'),
    children: [
      {
        path: '/user-profile',
        name: 'user-profile',
        component: () => import('../views/user/user-profile.vue'),
        meta: {
          title: "个人资料"
        }
      },
      {
        path: '/editPass',
        name: 'editPass',
        component: () => import('../views/user/editPass.vue'),
        meta: {
          title: "修改密码"
        }
      },
      {
        path: '/operationLog',
        name: 'operationLog',
        component: () => import('../views/user/operationLog.vue'),
        meta: {
          title: "操作日志"
        }
      },
      {
        path: '/myFavorite',
        name: 'myFavorite',
        component: () => import('../views/user/myFavorite.vue'),
        meta: {
          title: "我的收藏"
        }
      },
    ]
  },
  {
    path: '/nextWeekCourse',
    name: 'nextWeekCourse',
    component: () => import('../views/nextWeekCourse.vue')
  },
  {
    path: '/documentCenter',
    name: 'documentCenter',
    component: () => import('../views/DocumentCenter.vue')
  },
  {
    path: '/dataCenter',
    name: 'dataCenter',
    component: () => import('../views/DataCenter.vue')
  },
]



const router = new VueRouter({
  routes,
  mode: 'history' // 设置为历史模式
})

const ticketFilter = (ticket, to, from, next) => {
  if (ticket) {
    localStorage.setItem('ticket', ticket);
    sendTicket(ticket).then(res => {
      if (res.code === 200) {
        localStorage.setItem("CRP", res.data.user.username)
        localStorage.setItem("authToken", res.data.token)
        // 金智登录的userId
        localStorage.setItem("userId", res.data.user.id)
        next('/teacher');
      } else {
        // 校验失败则使用管理员账号来打通各接口权限
        let token = localStorage.getItem("authToken")
        passwordAndTokenFilter(token, to, from, next)
        // next(); // 继续导航到请求页面
      }
    }).catch(() => {
      let token = localStorage.getItem("authToken")
      passwordAndTokenFilter(token, to, from, next)
      // next(); // 处理请求失败的情况
    });
  } else {
    const storedTicket = localStorage.getItem('ticket');
    if (!storedTicket) {
      window.location.href = 'http://authserver.lzzy.net/authserver/login?service=http://portal.lzpu.edu.cn/';
      // if (to.path !== '/') { // 假设你有一个登录页面
      //   // next('/login'); // 或者启动第三方登录
      //   window.location.href = 'http://authserver.lzzy.net/authserver/login?service=http://portal.lzpu.edu.cn';
      // } else {
      //   next();
      // }
    } else {
      next();
    }
  }
}

//口令验证法
const passwordAndTokenFilter = (token, to, from, next) => {
  if (token === null || token === undefined || true) {
    let reqObj = {
      phone: "13217721025",
      password: "xcvisy@163.com"
    }
    login(reqObj).then(rsp => {
      if (rsp.code === 200) {
        localStorage.setItem('authToken', rsp.data.token);
        // token校验用的userId
        localStorage.setItem('validateUserId', 15)

        // let roleId=
        let tmp = res
      } else {
        next(); // 继续导航到请求页面
      }
    }).catch(error => {
      console.log("登录异常", error)
      next(); // 处理请求失败的情况
    });
  }


}

// 添加全局前置守卫
// router.beforeEach((to, from, next) => {
//   const params = new URLSearchParams(window.location.search);
//   const ticket = params.get('ticket');
//   const token = localStorage.getItem("authToken");
//   // ticketFilter(ticket, to, from, next);
//   //方便本地测试
//   // passwordAndTokenFilter(token, to, from, next);
//   // localStorage.setItem("userId", 15)

//   const userId = localStorage.getItem("userId")
//   getUserById(userId).then(user => {
//     if (user.code == 200) {
//       store.dispatch('setUserInfo',user.data) // 调用action更新角色
//       getRole(user.data.roleId).then(role => {
//         if (role.code == 200) {
//           localStorage.setItem("roleName", role.data[0].name)
//           localStorage.setItem("username",user.data.username)
//         }
//       })
//     }
//   })
// });

// 路由白名单，不需要登录就能浏览的页面
const whiteList = ['/login']


router.beforeEach((to, from, next) =>{
  const token = localStorage.getItem('authToken');
  console.log('router.beforeEach token',token)
  console.log('to', to)
  if(token){
    if( to.path === '/login'){
      next({path: '/'})
    } else if (whiteList.indexOf(to.path) !== -1) {
        next()
    } else {
        console.log(store.state)
        console.log(store.getters.roles)
        console.log(store.getters.username)
        if (!store.getters.username) {
            // 判断当前用户是否已拉取完user_info信息
            console.log('没有角色！！，重新拉取用户信息')

            store.dispatch('GetInfo').then(() => {
              console.log('跳转到主页');
              next() // hack方法 确保addRoutes已完成
            }).catch(err => {
                store.dispatch('LogOut').then(() => {
                  next({ path: '/' })
                })
            })
        } else {
            next()
        }
    }
  }else{
    const loginType = to.query.loginType
    console.log('loginType',loginType)
    // 没有token直接跳转到登录
    // if (whiteList.indexOf(to.path) !== -1) {
    //   // 在免登录白名单，直接进入
    //   next()
    // } else
    if(loginType == 'password'){
      // 账号密码登录
      next(`/login?redirect=${encodeURIComponent(to.fullPath)}`) // 否则全部重定向到登录页
    }else {
      // 统一认证登录
      window.location.href = 'http://authserver.lzzy.net/authserver/login?service=http://portal.lzpu.edu.cn/';
    }
  }
})


export default router
